﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QAudioFormat>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QAudioFormat format;
    format.setSampleRate(8000);                        //设置采样率
    format.setChannelCount(1);                          //设定声道数目，mono(平声道)的声道数目是1；stero(立体声)的声道数目是2
    format.setSampleSize(16);                           //设置采样大小
    format.setCodec("audio/pcm");                       //设置编码器，"audio/pcm"在所有的平台都支持
    format.setSampleType(QAudioFormat::SignedInt);      //设置采样类型
    format.setByteOrder(QAudioFormat::LittleEndian);    //设定高低位的，LittleEndian（低位优先）/LargeEndian(高位优先)
    QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();

    if(!info.isFormatSupported(format))                 //格式是否支持;
    {
        format = info.nearestFormat(format);
    }

    outPut = new QAudioOutput(format, this);            //输出音频
    inPut = new QAudioInput(format, this);              //输入音频

    outPutDevice = outPut->start();
    inPutDevice = inPut->start();

    startTimer(30);                                     //定时器
}

MainWindow::~MainWindow()
{
    inPut->stop();
    outPut->stop();
    delete inPut;
    delete outPut;
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *e)
{
    QByteArray audio = inPutDevice->readAll();          //获取音频数据
    outPutDevice->write(audio);                         //播放音频数据

}

